/**
 * Created by Administrator on 2016/12/2.
 */
angular.module("myApp", ["ionic"])
    .controller("myCtrl", function($scope, Projects){
        $scope.projects = Projects.all();
        $scope.activeProjects = $scope.projects[Projects.getLastActiveIndex()];

        var createProject = function(projectTitle){
            var newProject = Projects.newProject(projectTitle);
            console.log(typeof($scope.projects));
            $scope.projects.push(newProject);
            Projects.save($scope.projects);
        };
        $scope.createNewProject = function(){
            var projectTitle = prompt("Project name");
            if(projectTitle){
                createProject(projectTitle);
            }
            console.log(projectTitle);
        };
    })
    .factory("Projects", function () {
        return {
            all: function(){
                var projectString = window.localStorage["projects"];
                if(projectString){
                    return angular.fromJson(projectString);
                }
                return [];
            },
            save: function(projects){
                window.localStorage["projects"] = angular.toJson(projects);
            },
            newProject: function(projectTitle){
                return {
                    title:projectTitle,
                    tasks:[]
                };
            },
            getLastActiveIndex: function(){
                return parseInt(window.localStorage["lastActiveIndex"]);
            },
            setLastActiveIndex: function(index){
                window.localStorage["lastActiveIndex"] = index;
            }
        };
    });